package top.zlcode.friend.aspect;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.zlcode.common.core.constants.Constants;
import top.zlcode.common.core.context.UserContextHelper;
import top.zlcode.common.core.enums.ResultCode;
import top.zlcode.common.security.exception.ServiceException;
import top.zlcode.friend.domain.user.vo.UserVO;
import top.zlcode.friend.manager.UserCacheManager;

import java.util.Objects;

/**
 * 用户状态检查切面类
 * 实现了AOP切面编程，通过注解方式实现对目标方法的增强
 */
@Aspect
@Component
public class UserStatusCheckAspect {

    @Autowired
    private UserCacheManager userCacheManager;

    /**
     * 前置通知方法：在被 @CheckUserStatus 注解标记的方法执行前执行
     * 主要功能：验证用户是否存在以及用户账号是否被禁用
     * @param point 连接点对象，包含了目标方法的相关信息
     */
    @Before(value = "@annotation(top.zlcode.friend.aspect.CheckUserStatus)")
    public void before(JoinPoint point){
        Long userId = UserContextHelper.getUserId();
        UserVO user = userCacheManager.getUserById(userId);
        if (user == null) {
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        if (Objects.equals(user.getStatus(), Constants.FALSE)) {
            throw new ServiceException(ResultCode.FAILED_USER_BANNED);
        }
    }
}
